/* eslint-disable no-async-promise-executor */
import * as singleSpa from "single-spa";
import axios from "axios";
const runScript = async (url) => {
  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    if (script.readyState) {
      //IE onreadystatechange
      script.onreadystatechange = resolve;
    } else {
      script.onload = resolve;
    }
    script.onerror = reject;
    const firstScript = document.getElementsByTagName("script")[0];
    firstScript.parentNode.insertBefore(script, firstScript);
  });
};

/*
 * getManifest：远程加载manifest.json 文件，解析需要加载的js
 * */
const getManifest = (url, bundle) =>
  new Promise(async (resolve) => {
    // 可以预加载一些 复用的公共js
    // await runScript(
    //   "https://image.bitautoimg.com/das/fe/yi-platform/basepro/vuex/3.0.1/vuex.min.js"
    // );
    const { data } = await axios.get(url);
    console.log("data", data);
    const { entrypoints, publicPath } = data;
    const assets = entrypoints[bundle].assets;
    let i = 0;
    for (let item of assets) {
      let url = publicPath + item;
      await runScript(url)
        .then(() => {
          if (i === assets.length - 1) {
            resolve();
          }
          i++;
        })
        .catch((err) => {
          console.log("==!!!!====加载失败", url, err);
        });
    }
  });

const registerApp = (urlPath) => {
  window.VueMain = window.Vue;
  let appList = singleSpa.checkActivityFunctions();
  if (appList.includes("sub-test")) {
    singleSpa.navigateToUrl(urlPath);
    return;
  }
  // window.Vue = undefined;
  singleSpa.registerApplication(
    //注册微前端服务
    "sub-test",
    async () => {
      // 注册用函数，
      // return 一个singleSpa 模块对象，模块对象来自于要加载的js导出
      // 如果这个函数不需要在线引入，只需要本地引入一块加载：
      // () => import('xxx/main.js')
      let exappUrl;
      if (process.env.NODE_ENV == "development") {
        exappUrl = "http://localhost:3000/manifest.json";
      } else {
        exappUrl = "/sub-test/manifest.json";
      }
      await getManifest(exappUrl, "app").then(() => {});
      singleSpa.start(); // 启动
      return window.singleSubTest;
    },

    (location) => location.pathname.startsWith("/sub-test"), // 配置微前端模块前缀,
    () => {
      //这里可以往 子项目传递父项目 变量
      return {};
    }
  );
};

export default registerApp;
